import { Component, OnInit } from '@angular/core';

import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Menu } from "../../../../entity/menu.model";
import { FormBuilder, FormControl, Validators } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { MenuService } from "../../../../service/menu.service";
import { Subject } from "rxjs/Rx";

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';


@Component({
  selector: 'app-menu-edit',
  templateUrl: './menu-edit.component.html',
  styleUrls: ['./menu-edit.component.css']
})
export class MenuEditComponent extends BladeContainerBase<Menu> {
  public menusItems: Menu[] = [];
  //是一个可观察的事件流中的生产者
  private searchTerms = new Subject<any>();
  private result: Observable<any>;

  constructor(
    private fb: FormBuilder,
    private menuService: MenuService
  ) {
    super(fb);
  }


  ngOnInit(): void {
    this.initMenu();
    //编辑时注册按钮和按钮命令    
    if (!this.isNew) {
      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      let parentMenu: Menu = this.parentEntity.parent;
      this.currentEntity = new Menu(0, "", "", "", "", 0, 0);
      this.currentEntity.parentId = parentMenu ? parentMenu.menuId : 0;
    }
    super.ngOnInit();
  }



  /**
   * 重新构建菜单
   * 
   * @private
   * @memberof MenuEditComponent
   */
  private initMenu() {
    this.menusItems = [];

    let menus: Menu[] = this.parentEntity.menus;

    menus.forEach(menu => {
      let menuItme: Menu = new Menu(
        menu.menuId,
        menu.menuName,
        menu.menuSubName,
        menu.menuPath,
        menu.menuIcon,
        menu.menuSeq,
        menu.parentId
      );
      let name = "|";
      for (let i = 0; i < menu.menuLevel; i++) {
        name += "— ";
      }
      menuItme.menuName = `${name}${menuItme.menuName}`;
      this.menusItems.push(menuItme);
    });
    
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return this.hasChange();
  }
  /**
   * 创建表单
   * 
   * 
   * @memberof DicKeyEditComponent
   */
  createForm() {
 
    this.formGroup = this.fromBuider.group({
      "parentId": [this.currentEntity.parentId, [
        Validators.required,
      ]],
      "menuName": [this.currentEntity.menuName, [
        Validators.required,
        Validators.maxLength(100),
      ], (control: FormControl): any => this.menuNameAsnyValidator(control)],
      "menuSubName": [this.currentEntity.menuSubName, [
        Validators.maxLength(100)
      ]],
      "menuPath": [this.currentEntity.menuPath, [
        Validators.maxLength(100)
      ]],
      "menuSeq": [this.currentEntity.menuPath, [
        Validators.maxLength(100)
      ]],
      "menuIcon": [this.currentEntity.menuIcon, [
        Validators.required,
        Validators.maxLength(50)
      ]],
    });

  }
  /**
     * 异步校验menuName是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof DicKeyEditComponent
     */
  menuNameAsnyValidator(control: FormControl): any {
      return this.menuService.hasMenuByMenuName(control.value, this.currentEntity.parentId, this.currentEntity.menuId)
        .map(res => res ? { exist: true } : null);
  }


  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      'menuName': '',
      'menuSubName': '',
      'menuPath': '',
      'menuIcon': '',
      'menuSeq': '',
    };
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {
      'parentId': {
        'required': '父级菜单。',
      },
      'menuName': {
        'required': '菜单名称不能为空。',
        'maxlength': '菜单名称不能多于100个字符长度。',
        'exist': '菜单名称已存在',
      },
      'menuSubName': {
        'maxlength': '菜单子名称不能多于100个字符长度。',
      },
      'menuPath': {
        'maxlength': '路由地址不能多于50个字符长度。',
      },
      'menuIcon': {
        'required': '图标不能为空。',
        'maxlength': '图标不能多于50个字符长度。',
      },
      'menuSeq': {
        'required': '排序不能为空',
      }
    };
  }

  /**
     * 创建一个数据字典键
     * 
     * 
     * @memberof DicKeyEditComponent
     */
  onCreate() {
    this.create();
  }


  create(): Promise<boolean> {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as Menu;
      this.currentEntity.menuName = formValue.menuName;
      this.currentEntity.menuSubName = formValue.menuSubName;
      this.currentEntity.menuPath = formValue.menuPath;
      this.currentEntity.menuIcon = formValue.menuIcon;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.menuSeq = formValue.menuSeq;
      return this.menuService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  saveChange(): Promise<boolean> {
    if (this.canSaveChange(this.currentBlade)) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as Menu;
      this.currentEntity.menuName = formValue.menuName;
      this.currentEntity.menuSubName = formValue.menuSubName;
      this.currentEntity.menuPath = formValue.menuPath;
      this.currentEntity.menuIcon = formValue.menuIcon;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.menuSeq = formValue.menuSeq;
      return this.menuService.update(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);

    }
  }
}




// WEBPACK FOOTER //
// ./src/app/module/admin/menu/menu-edit/menu-edit.component.ts